#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
using namespace std;
class Sem
{
  private:
    sem_t sem;
  public:
    Sem(int num)
    {
      sem_init(&sem,0,num);
    }
    void P()
    {
      sem_wait(&sem);
    }
    void V()
    {
      sem_post(&sem);
    }
    ~Sem()
    {
      sem_destroy(&sem);
    }
};
Sem sem(1);
int tickets=100;
void* Gettickets(void* arg)
{
  string s=(char*)arg;
  while(true)
  {
    sleep(1);
    sem.P();
    if(tickets>0)
    {
      usleep(10000);
      cout<<s<<"get tickets:"<<tickets--<<endl;
      sem.V();
    }
    else 
    {
      sem.V();
      break;
    }
  }
  pthread_exit((void*)0);
}
int main()
{
  pthread_t t1,t2,t3;
  pthread_create(&t1,NULL,Gettickets,(void*)"thread t1");
  pthread_create(&t2,NULL,Gettickets,(void*)"thread t2");
  pthread_create(&t3,NULL,Gettickets,(void*)"thread t3");
  pthread_join(t1,NULL);
  pthread_join(t2,NULL);
  pthread_join(t3,NULL);
  return 0;
}
